<template>
  <div id="address">
    <div v-show="this.$route.path == '/addr'">
      <van-address-list
        v-model="cid"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
      />
      <van-button
        class="submit"
        type="info"
        round
        block
        @click="chooseAddr(cid)"
        >选择地址</van-button
      >
    </div>
    <router-view :addrobj="addrobj"></router-view>
  </div>
</template>

<script>
import { Toast } from "vant";
import { GetAddr, GetOneAddr } from "../util/request/api";
import { mapActions, mapGetters } from "vuex";
export default {
  data() {
    return {
      cid: "",
      list: [],
      addrobj: {},
    };
  },
  methods: {
    chooseAddr(id) {
      this.changeAddrAction(id);
      this.$router.push("/order");
    },
    ...mapActions(["changeAddrAction"]),
    onAdd() {
      this.$router.push("/addaddr");
    },
    onEdit(item) {
      this.addrobj = item;
      this.$router.push("/editaddr");
    },
  },
  mounted() {
    GetAddr(this.uid)
      .then((res) => {
        if (res.list == null) {
          this.list = [];
          return;
        }
        res.list.forEach((item) => {
          let obj = {
            id: item.id,
            name: item.username,
            tel: item.userphone,
            address: item.location + item.useraddress,
            isDefault: item.status == 1 ? true : false,
          };
          this.list.push(obj);
        });
        let nitem = this.list.filter((item) => {
          return item.isDefault == true;
        });
        this.cid = nitem[0].id;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  computed: {
    ...mapGetters(["getChosenAddr"]),
    uid: function () {
      return JSON.parse(sessionStorage.getItem("user")).uid;
    },
  },
};
</script>

<style lang="less" scoped>
#address {
  .submit {
    width: 3.43rem;
    height: 0.4rem;
    position: fixed;
    bottom: 0.5rem;
    left: 0.15rem;
  }
  .van-address-list__bottom {
    background: transparent;
  }
}
</style>